import { FormData } from '@/pages/historyReplay/components/SearchForm.tsx';
import { FC, useEffect, useState } from 'react';
import { useCatch } from '@/hooks';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import HistoryReplayServices from '@/api/services/historyReplayServices.ts';
import { Table, TableProps, Tooltip } from 'antd';
import { ParkingLocationInfo } from '#/entity.ts';
import dayjs from 'dayjs';
import { Page } from '#/api.ts';

type Props = {
  searchParams?: FormData;
};

const ParkingLocationTable: FC<Props> = ({ searchParams }) => {
  const catchFn = useCatch();
  const [page, setPage] = useState<Page>({ page: 1, limit: 10, order: 'id DESC' });

  useEffect(() => {
    if (searchParams) {
      setPage({
        page: 1,
        limit: 10,
        order: 'id DESC',
      });
    }
  }, [searchParams]);

  const { data, isFetching } = useQuery({
    placeholderData: keepPreviousData,
    queryKey: ['parkingLocationList', searchParams],
    queryFn: () =>
      catchFn(() =>
        HistoryReplayServices.getParkingLocationList({
          plateNumber: searchParams!.plateNumber,
          startTime: searchParams!.startTime.format('YYYY-MM-DD HH:mm:ss'),
          endTime: searchParams!.endTime.format('YYYY-MM-DD HH:mm:ss'),
          space: searchParams!.space,
          duration: searchParams!.duration,
        }),
      ),
    select: ({ data }) => data,
    enabled: !!searchParams,
    staleTime: 6000,
    gcTime: 6000,
  });

  const tableProps: TableProps<ParkingLocationInfo> = {
    size: 'small',
    columns: [
      {
        title: '停车开始时间',
        dataIndex: 'parkStartTime',
        render: (value) => dayjs(value).format('YYYY-MM-DD HH:mm:ss'),
        width: 200,
      },
      {
        title: '停车结束时间',
        dataIndex: 'parkEndTime',
        render: (value) => dayjs(value).format('YYYY-MM-DD HH:mm:ss'),
        width: 200,
      },
      { title: '停车时长', dataIndex: 'duration', render: (value) => `${value}秒`, width: 100 },
      {
        title: '累计停车时长',
        dataIndex: 'parkDuration',
        render: (value) => `${value}秒`,
        width: 150,
      },
      {
        title: '经纬度',
        dataIndex: 'lng',
        render: (_value, record) => {
          return `${record.lng},${record.lat}`;
        },
        width: 200,
      },
      {
        title: '位置',
        dataIndex: 'address',
        ellipsis: true,
        render: (value) => {
          return <Tooltip title={value}>{value}</Tooltip>;
        },
        width: 200,
      },
    ],
    dataSource: data,
    rowKey: 'id',
    loading: isFetching,
    pagination: {
      current: page.page,
      pageSize: page.limit,
      showTotal: (total) => `共 ${total} 条数据`,
      onChange: (page, pageSize) => setPage({ page: page, limit: pageSize, order: 'id DESC' }),
    },
    scroll: {
      y: 140,
    },
  };

  return (
    <>
      <Table {...tableProps}></Table>
    </>
  );
};

export default ParkingLocationTable;
